<?php
namespace control;
/*
*档案销毁类
*/


class archiveRuinClass extends adIndexClass
{
    private const title = '档案销毁';
    private const page = 'archiveRuin';
    private const table = 'archive_ruin';
    private const tableMx = 'archive_ruin_detail';
    private const stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'ruinedSearch':
                $tr = [
                    'workFlow'          => [
                        'name'  => '销毁状态',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'typeId' => [
                        'name'  => "档案分类",
                        'width' => 100,
                    ],
                    'cNo'  => [
                        'name'  => "归档号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '题名',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'locationId'          => [
                        'name'  => '存放位置',
                        'width' => 150,
                    ],
                    'pageNum'          => [
                        'name'  => '页数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'partNum'          => [
                        'name'  => '份数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fileDate'          => [
                        'name'  => '文件形成日期',
                        'width' => 100,
                    ],
                    'archiveDate'          => [
                        'name'  => '归档日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'saveTime'          => [
                        'name'  => '保管期限',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '销毁原因',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'ruinDate'          => [
                        'name'  => '销毁日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'ruinStid'          => [
                        'name'  => '销毁人',
                        'width' => 100,
                    ]
                ];
                break;
            default:
                $tr = [
                    'workFlow'          => [
                        'name'  => '销毁状态',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'typeId' => [
                        'name'  => "档案分类",
                        'width' => 100,
                    ],
                    'cNo'  => [
                        'name'  => "归档号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '题名',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'locationId'          => [
                        'name'  => '存放位置',
                        'width' => 150,
                    ],
                    'pageNum'          => [
                        'name'  => '页数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'partNum'          => [
                        'name'  => '份数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fileDate'          => [
                        'name'  => '文件形成日期',
                        'width' => 100,
                    ],
                    'archiveDate'          => [
                        'name'  => '归档日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'saveTime'          => [
                        'name'  => '保管期限',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '销毁原因',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'applyDate'          => [
                        'name'  => '申请日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '审批状态',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "分类" => selectMultiple(array("name" => "typeId", 'table' => "archive_type", 'sqlId' => 'id', 'sqlField' => 'name')),
                    "题名"     => text(array("name" => "name")),
                    "归档号"     => text(array("name" => "orderNo")),
                ],
                [
                    '存放位置'   => selectMultiple(array("name" => "locationId", 'table' => "archive_cabinet", 'sqlId' => 'id', 'sqlField' => 'name')),
                    "销毁原因"     => text(array("name" => "text")),
                    "保管期限" => select(array("name" => "saveTime", "option" =>explode('，',para('archiveSaveTime')))),
                ],
                [
                    "审批状态" => select(["name" => "state", 'option' => self::stateOption]),
                    "申请日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">移除</span>\n";
        }
        if ($this->power(self::page, "ruin")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','destroyFile',{})\" class='spanButton'>销毁</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "c.orderNo" => $this->post('orderNo'),
            "c.name" => $this->post('name'),
            "b.text" => $this->post('text'),
        );
        //全等查询数组
        $equal = array(
            'b.workFlow' => '待销毁',
            "c.typeId" => $this->post('typeId'),//公文种类
            "state" => $this->post('state'),
            "c.locationId" => $this->post('locationId'),
            "c.saveTime" => $this->post('saveTime'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "a.applyDate");
        }
        if (!$this->power(self::page, 'seeAll')) {
            $and .= " and a.staffId = '" . self::$stid . "'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.applyDate desc,b.list',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'field' => "b.*,c.typeId,c.name,c.orderNo as cNo,c.locationId,c.partNum,c.pageNum,c.fileDate,c.saveTime,c.archiveDate,a.state,a.applyDate",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['orderId'] . "')"),
                "edit" => $array['state'] != '草稿' ? [] : array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['orderId'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "typeId":
                        $row[] = dossierClass::getTypeName($array['typeId']);
                        break;
                    case "locationId":
                        $row[] = dossierClass::getPosititonName($array['locationId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'single' => $where,
            'field'  => "ifnull(sum(c.partNum),0) as partNum",
        ]);
        $total    = [
            'partNum'        => $totalQuery['partNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 100),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>". $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function ruinedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "分类" => selectMultiple(array("name" => "typeId", 'table' => "archive_type", 'sqlId' => 'id', 'sqlField' => 'name')),
                    "题名"     => text(array("name" => "name")),
                    "归档号"     => text(array("name" => "orderNo")),
                ],
                [
                    '存放位置'   => selectMultiple(array("name" => "locationId", 'table' => "archive_cabinet", 'sqlId' => 'id', 'sqlField' => 'name')),
                    "销毁原因"     => text(array("name" => "text")),
                    "保管期限" => select(array("name" => "saveTime", "option" =>explode('，',para('archiveSaveTime')))),
                ],
                [
                    "销毁日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 已销毁
     *
     */
    public function ruined(): bool|string
    {
        $html = $this->ruinedOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 已借阅
     * @return bool|string
     */
    public function ruinedSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "c.orderNo" => $this->post('orderNo'),
            "c.name" => $this->post('name'),
            "b.text" => $this->post('text'),
        );
        //全等查询数组
        $equal = array(
            'b.workFlow' => '已销毁',
            "c.typeId" => $this->post('typeId'),//公文种类
            "a.state" => $this->post('state'),
            "c.locationId" => $this->post('locationId'),
            "c.saveTime" => $this->post('saveTime'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "ruinDate");
        }
        if (!$this->power(self::page, 'seeAll')) {
            $and .= " and a.staffId = '" . self::$stid . "'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.ruinDate desc,b.list',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'field' => "b.*,c.typeId,c.name,c.orderNo as cNo,c.locationId,c.partNum,c.pageNum,c.fileDate,c.saveTime,c.archiveDate",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['orderId'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "typeId":
                        $row[] = dossierClass::getTypeName($array['typeId']);
                        break;
                    case "locationId":
                        $row[] = dossierClass::getPosititonName($array['locationId']);
                        break;
                    case "ruinStid":
                        $row[] = self::findStaff($array['ruinStid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'single' => $where,
            'field'  => "ifnull(sum(c.partNum),0) as partNum",
        ]);
        $total    = [
            'partNum'        => $totalQuery['partNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 100),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 销毁
     */
    public function destroyFile(): bool|string
    {
        $formName = 'listForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "销毁日期：" => text(array('name' => 'signTime', 'laydate' => [], 'value' => $this->date)),
            ),
        )));
        //返回
        return $this->layer(array("title" => "销毁", "height" => 150, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 销毁
     */
    public function destroyFileEdit(): bool|string
    {
        $idArr = $this->post('listId');
        if (!$this->power(self::page, "ruin")) {
            $json['warn'] = "你没有" . self::title . "的销毁权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($this->post('signTime'))) {
            $json['warn'] = '请选择销毁日期';
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $mx = query(self::tableMx, "id = '$id'");
                $info = query(self::table, "id = '$mx[orderId]'");
                $archive_file= query('archive_file', "id = '$mx[fileId]'");
                if ($info['state'] != '已通过') {
                    $text .= $this->control['name'] . "销毁档案【{$archive_file['name']}】， id：{$id} 失败：还未审核通过<br>";
                } else {
                    $warn = update(array('table' => self::tableMx, 'field' => ['workFlow' => '已销毁','ruinStid'=>self::$stid, 'ruinDate' => $this->post('signTime')], 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        update(array('table'=>'archive_file','field'=>['fileState'=>2],'where'=>"id = '$archive_file[id]'"));
                        $x++;
                        //发送待办
                        $text .= $this->control['name'] . "销毁档案【{$archive_file['name']}】， id：{$id}成功，销毁日期:{$this->post('signTime')}<br>";
                    } else {
                        $text .= $this->control['name'] . "销毁档案【{$archive_file['name']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功销毁了{$x}个档案，详情请查看系统日志";
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }



    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $listId = $this->get('listId');
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];

        $tr[] = [' ', '档案分类', '归档号', '题名','存放位置', '页数', '份数', '文件形成日期','归档日期','保管期限', '销毁原因'];
        $totalArr = ['partNum'=>0];
        if (!empty($listId)) {
            $idCollection = explode(',', $listId);
            foreach ($idCollection as $k=>$fileId) {
                $archive_file = query('archive_file', " id = '$fileId'");
                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
                    hidden(array('name' => 'cid[]', 'value' => $fileId)),
                    dossierClass::getTypeName($archive_file['typeId']),
                    $archive_file['orderNo'],
                    $archive_file['name'],
                    dossierClass::getPosititonName($archive_file['locationId']),
                    $archive_file['pageNum'],
                    "<span class='partNum'>".$archive_file['partNum']."</span>",
                    $archive_file['fileDate'],
                    $archive_file['archiveDate'],
                    $archive_file['saveTime'],
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' =>'')),
                ];
                $totalArr['partNum'] += $archive_file['partNum'];
            }
        } else {
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $k=>$array) {
                $archive_file = query('archive_file', " id = '$array[fileId]'");
                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                    hidden(array('name' => 'cid[]', 'value' => $array['fileId'])),
                    dossierClass::getTypeName($archive_file['typeId']),
                    $archive_file['orderNo'],
                    $archive_file['name'],
                    dossierClass::getPosititonName($archive_file['locationId']),
                    $archive_file['pageNum'],
                    "<span class='partNum'>".$archive_file['partNum']."</span>",
                    $archive_file['fileDate'],
                    $archive_file['archiveDate'],
                    $archive_file['saveTime'],
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
                ];
                $totalArr['partNum'] += $archive_file['partNum'];
            }
        }
        $total = [
            6 => "<span id='total_partNum'>".$totalArr['partNum']."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $smallButton = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name={$this->get('cla')}EditForm]').serialize())">选择档案</span>
efo;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "申请人：" => selectMultiple(["name" => "staffId",  'title' => '请选择', 'table' => 'staff', 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['staffId']?:self::$stid]),
                    must . "申请日期：" => text(["name" => "applyDate", 'laydate' => [], "value" => $info['applyDate']?:$this->date]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '明细',
            'button' => $smallButton,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' =>$id]),
        ]);
        //返回
        return $this->tab($data) . $this->editJs();
    }

    public function editJs(): string
    {
        return <<<eof
<script>
function getStaffName(e){
    let stid = e.value;
    if (stid){
        $.post(root+'control/adIndex.html?cla=certificateBorrow&fun=getStffName',{stid:stid},function(res) {
           $("[name='stName']").val(res.name);
        },'json')
    }
}
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $('#archiveRuinAddMx').hide()
        $("#materialTable tbody").append(res.html);
        calculateTotal();
        resetNumber($("#materialTable"))
    },'json');
}
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let num = 0
    table.find(".partNum").each(function(index){
        if($(this).text()){
          num+=Number($(this).text());
        }
    })
    $("#total_partNum").text(num);
}
</script>
eof;

    }
    /**
     *
     * @return bool|string
     */
    public function addMx(): bool|string
    {
        $html =
            selectMultiple(array("name" => "typeId","title" => "分类", 'table' => "archive_type", 'sqlId' => 'id', 'sqlField' => 'name')) .
            text(array("name" => "orderNo", "title" => "归档号")) .
            text(array("name" => "name", "title" => "题名")) .
            hidden(array('name' => 'cid', 'value' => $this->post('cid') ? implode(',', $this->post('cid')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMxSearch(): bool|string
    {
        $cid = $this->post('cid') ? explode(',', $this->post('cid')) : [];
        $where = " 1=1 and id not in ('" . implode("','", $cid) . "')";
        $and = "and fileState =0";
        $like = [
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
        ];
        $equal = [
            'typeId' => $this->post('typeId'),
        ];
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "archive_file",
            "where" => $where,
            'pageNum' => 50,
            "order" => "time ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '分类', '归档号', '题名'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                dossierClass::getTypeName($array['typeId']),
                $array['orderNo'],
                $array['name'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit(): bool|string
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择档案';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $archive_file = query('archive_file', " id = '$mxId'");
                $id = self::getId();
                $type = dossierClass::getTypeName($archive_file['typeId']);
                $location = dossierClass::getPosititonName($archive_file['locationId']);
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'cid[]', 'value' => $mxId)),
                    $type,
                    $archive_file['orderNo'],
                    $archive_file['name'],
                    $location,
                    $archive_file['pageNum'],
                    "<span class='partNum'>".$archive_file['partNum']."</span>",
                    $archive_file['fileDate'],
                    $archive_file['archiveDate'],
                    $archive_file['saveTime'],
                    text(array('name' => 'mxText[]', 'class' => 'text')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId');
        $cidArr = $this->post('cid');
        $mxTextArr = $this->post('mxText');

        $field = [
            'staffId' => $this->post('staffId'),
            'applyDate' => $this->post('applyDate'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'staffId' => '申请人',
            'applyDate' => '申请日期',
        ];
        $rules = [
            'staffId' => 'required',
            'applyDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择需要销毁的档案';
        } elseif (static::is_null_array($cidArr)) {
            $json['warn'] = '请选择需要销毁的档案';
        } else {
            foreach ($mxIdArr as $k => $mxId) {
                $archive_file = query('archive_file', "id = '$cidArr[$k]'");
                if ($archive_file['fileState']){
                    $json['warn'] = "归档号为【{$archive_file['orderNo']}】的档案已借出或销毁";
                    break;
                }
            }
            if (empty($json['warn'])){
                $this->startTrans();
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page,[
                        'prefix' => 'DAXH' . date('Ymd'),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => '',
                    ],$field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $userNo,
                        'state' => '草稿',
                        'stid' => self::$stid,
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
                }
                foreach ($mxIdArr as $k => $mxId) {
                    $mx = query(self::tableMx, "id = '$mxId'");
                    if (empty($mx['id'])) {
                        $warn = static::insert(array(
                            'table' => self::tableMx,
                            'field' => [
                                'id' => $mxId,
                                'orderId' => $id,
                                'fileId' => $cidArr[$k],
                                'text' => $mxTextArr[$k],
                            ]
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::tableMx,
                            'field' => [
                                'text' => $mxTextArr[$k],
                            ],
                            'where'=>"id = '$mx[id]'"
                        ));
                    }
                    if (!in_array($warn, ["新增成功", "更新成功"])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }

                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    $this->commitTrans();
                    delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }

        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '档案销毁',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
        }
        $num = static::total(array('table'=>self::tableMx,"where"=>"orderId = '$info[id]' and workFlow ='已销毁'"));
        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿' && $num==0) {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    /*客户管理-客户详情页*/
    public function detail()
    {
        $info = query(self::table, "id = '" . $this->get('id') . "'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $tr[] = ['档案分类', '归档号', '题名','存放位置', '页数', '份数', '文件形成日期','归档日期','保管期限', '销毁原因','销毁日期','销毁人'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $total_tr = [5=>0];
            foreach ($result['array'] as $array) {
                $archive_file = query('archive_file', " id = '$array[fileId]'");
                $archive_file['orderNo'] = "<span class='link' onclick=\"newIframe('档案详情','" . root . "control/adIndex.html?cla=dossier&fun=detail&id=" . $array['fileId'] . "')\">" . $archive_file['orderNo'] . "</span>";
                $tr[] = [
                    dossierClass::getTypeName($archive_file['typeId']),
                    $archive_file['orderNo'],
                    $archive_file['name'],
                    dossierClass::getPosititonName($archive_file['locationId']),
                    $archive_file['pageNum'],
                    $archive_file['partNum'],
                    $archive_file['fileDate'],
                    $archive_file['archiveDate'],
                    $archive_file['saveTime'],
                    $array['text'],
                    $array['ruinDate'],
                    self::findStaff($array['ruinStid'])
                ];
                $total_tr[5] += $archive_file['partNum'];
            }
            //按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];

            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "申请人" => self::findStaff($info['staffId']),
                        "申请日期" => $info['applyDate'],
                        "备注" => $info['text'],
                        "单据编号" => $info['orderNo'],
                    ),
                    array(
                        "制单人" => self::findStaff($info['stid']),
                        "审核状态" => $info['state'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_tr)),
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?: $this->post('id');
        $type = $this->post('listId') ?'multiple':'single';
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有移除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            if ($type =='single'){
                foreach ($array as $id) {
                    $info = query(self::table, " id = '$id'");
                    if ($info['state'] != '草稿') {
                        //返回
                        $warn = "删除失败：不是草稿状态";
                    } else {
                        //删除audit表记录
                        delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                        //删除待办事项
                        delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                        //删除审批记录
                        delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                        //删除消息提醒
                        delete(array("table" => "message", "where" => " typeId = '$id' "));
                        //最后删除基本参数
                        delete(array("table" => self::table, "where" => " id = '$id' "));
                        delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                        //返回
                        $warn = "删除成功";
                        $x++;
                    }
                    $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
                }
            }else{
                foreach ($array as $id) {
                    $mx = query(self::tableMx, " id = '$id'");
                    $archive_file = query('archive_file', "id = '$mx[fileId]'");
                    if ($mx['workFlow'] == '已销毁') {
                        //返回
                        $warn = "删除失败：已销毁";
                    } else {
                        delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                        //返回
                        $warn = "移除成功";
                        $x++;
                    }
                    $text .= "归档号为【" . $archive_file['orderNo'] . "】的档案" . $warn . "。<br>";
                    if (static::total(array('table'=>self::tableMx,'where'=>"orderId = '$mx[orderId]'")) ==0){
                        //删除audit表记录
                        delete(array('table' => 'audit', 'where' => "targetId = '$mx[orderId]'"));
                        //删除待办事项
                        delete(array("table" => "backlog", "where" => " typeId = '$mx[orderId]' "));
                        //删除审批记录
                        delete(array("table" => "auditing_follow", "where" => " typeId = '$mx[orderId]' "));
                        //删除消息提醒
                        delete(array("table" => "message", "where" => " typeId = '$mx[orderId]' "));
                        //最后删除基本参数
                        delete(array("table" => self::table, "where" => " id = '$mx[orderId]' "));
                    }
                }
            }

            //添加日志
            if ($text){
                $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
                $this->logText(array("type" => self::page, "text" => $text));
            }
            $_SESSION['warn'] = "删除了" . $x . "个档案销毁数据，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
